package com.sh.myFilterFactory;

import com.sh.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

@Component
public class TokenFilterFactory extends AbstractGatewayFilterFactory<TokenFilterFactory.Config> {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public TokenFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                String token = request.getHeaders().getFirst("token");
                if (!jwtTokenUtil.isTokenExpired(token)) {
                    return chain.filter(exchange);
                } else {
                    return Mono.defer(() -> Mono.error(new RuntimeException("token已过期")));
                }
            }
        };
    }

    public static class Config {

    }
}